package preAuthorize

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"shop-common/library/serializer"
	"shop-common/library/variables"
	"shop-common/utils"
	"shop-common/utils/contextArgs"
	"time"
)

//todo 参考yami-shop编写一个简单的权限验证，通过context获取数据
/**
 * 接口权限判断工具
 */
func HasPermission(permission string) func(ctx *gin.Context) {
	return func(ctx *gin.Context) {
		isOK := hasPermission2(ctx, permission)
		if !isOK {
			ctx.JSON(http.StatusForbidden, &serializer.Response{
				Code:    http.StatusForbidden,
				Result:  nil,
				Message: http.StatusText(http.StatusUnauthorized),
				Type:    "error",
				Time:    time.Now().Unix(),
			})
			ctx.Abort()
			return
		}
		ctx.Next()
	}
}

func hasPermission2(ctx *gin.Context, permission string) bool {
	if permission == "" {
		return false
	}

	sub, err := contextArgs.GetRoles(ctx, "role")
	if err != nil {
		return false
	}

	for _, role := range sub {
		invalid := utils.StringIncludes(variables.GlobalRolePermission[role], permission)
		if invalid {
			return true
		}
	}

	return false
}

func hasPermission(ctx *gin.Context, permission string) bool {
	if permission == "" {
		return false
	}

	value, ok := ctx.Get("accessPerms")
	if !ok {
		return false
	}

	return utils.StringsIncludes(value.([]string), permission)
}

/*
sub, err := contextArgs.GetRoles(ctx, "role")
*/

/*
func CheckCasbinRole(roles []uint, obj, act string) (bool, error) {
	// 同一时间只允许一个请求执行校验, 否则可能会校验失败
	checkLock.Lock()
	defer checkLock.Unlock()
	for _, role := range roles {
		pass, err := variables.Enforcer.Enforce(fmt.Sprintf("%d", role), obj, act)
		if err != nil {
			return false, err
		}

		if pass {
			return true, nil
		}
	}

	return false, nil
}
*/
